import {Popconfirm,Divider,InputNumber,Input} from 'antd';
import ProTable from '@ant-design/pro-table';
import React, {useState, useEffect} from 'react';
import styles from "@/pages/Info/Edit/style.less";

const EditOvertimeSporadicTable = ({addUserList, protocolUserItems=[], saveFunction}) => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [clickedCancel, setClickedCancel] = useState(false);
  const [cacheOriginData, setCacheOriginData] = useState({});

  const columns = [
    {
      title: '工号',
      dataIndex: 'userId',
      disabled: true
    },
    {
      title: '姓名',
      dataIndex: 'userName',
      disabled: true
    },
    {
      title: '公司',
      dataIndex: 'orgName',
      disabled: true
    },
    {
      title: '部门',
      dataIndex: 'unitName',
      disabled: true
    },
    {
      title: '时长',
      dataIndex: 'longOverwork',
      render: (text, record) => {
        if (record.editable) {
          return (
            <InputNumber style={{width:'100%'}} value={text !== '-' ? text : 0} placeholder='0.5小时为单位' min={0} max={4} step={0.5} onChange={(e) => handleFieldChange(e, 'longOverwork', record.key)}/>
          )
        }
        return text !== '-' ? text + `小时` : 0;
      },
    },
    {
      title: '说明',
      dataIndex: 'remark',
      ellipsis:true,
      width: 200,
      render: (text, record) => {
        if (record.editable) {
          return (
            <Input value={record.remark ? record.remark : ''} onChange={(e) => handleFieldChange(e, 'remark', record.key)}/>
          )
        }
        return text;
      },
    },
    {
      title: '操作',
      key: 'action',
      width: '150px',
      render: (text, record) => {
        if (record.editable) {
          return (
            <span>
            <a onClick={(e) => updateRow(e, record.key, record.oid)}>保存</a>
            <Divider type="vertical"/>
            <a onClick={(e) => cancel(e, record.key)}>取消</a>
          </span>
          )
        }
        return (
          <span>
          <a onClick={(e) => toggleEditable(e, record.key)}>编辑</a>
          <Divider type="vertical"/>
          <Popconfirm title="是否确定删除？" cancelText='取消' okText='确认' onConfirm={(e) => remove(e, record)}>
            <a>删除</a>
          </Popconfirm>
        </span>
        )
      }
    },
  ];

  useEffect(()=>{
    setData(protocolUserItems.map((item, index) => ({key: 'had' + index, ...item})));
  },[protocolUserItems]);

  useEffect(() => {
    setLoading(true);
    if (addUserList.length > 0) {
      let newData = [...data];
      for (let i = 0; i < addUserList.length; i++) {
        let isContinue = false;
        for (let a = 0; a < data.length; a++) {
          if (data[a].oid === addUserList[i].oid)
            isContinue = true;
        }
        if (isContinue)
          continue;
        newData.push({
          oid:addUserList[i].oid,
          key: addUserList[i].oid || addUserList[i].key,
          userId: addUserList[i].code || addUserList[i].userId,
          orgName: addUserList[i].orgname || addUserList[i].orgName,
          unitName: addUserList[i].unitname || addUserList[i].unitName,
          userName: addUserList[i].name || addUserList[i].userName,
          longOverwork:0 || addUserList[i].longOverwork,
          remark:null || addUserList[i].remark,
        });
      }
      setData(newData);
      saveFunction(newData);
    }
    setLoading(false);
  }, [addUserList]);

  const handleFieldChange = (e, fieldName, key) => {
    const newData = [...data];
    const target = getRowByKey(key, newData);
    if (target) {
      target[fieldName] = e.target ? e.target.value : e;
      setData(newData);
    }
  };

  const remove = (e, record) => {
    setLoading(true);
    const newData = [...data];
    let datas = newData.filter(item => item.key !== record.key);
    saveFunction(datas);
    setLoading(false);
  };

  const updateRow = (e, rowKey) => {
    e.persist();
    if (clickedCancel) {
      setClickedCancel(false);
      return
    }
    toggleEditable(e, rowKey, 'save');
  };

  const cancel = (e, key) => {
    setClickedCancel(true);
    e.preventDefault();
    const newData = [...data]; // 编辑前的原始数据
    let cacheData = newData.map((item) => {
      if (item.key === key) {
        if (cacheOriginData[key]) {
          const originItem = {...cacheOriginData[key], editable: false};
          delete cacheOriginData[key];
          setCacheOriginData(cacheOriginData);
          return originItem
        }
      }
      return item
    });
    saveFunction(cacheData);
    setClickedCancel(false)
  };

  const getRowByKey = (key, newData) => (newData || data)?.filter((item) => item.key === key)[0]

  const toggleEditable = (e, key,type) => {
    e.preventDefault();
    const newData = data?.map((item) => ({...item}));
    const target = getRowByKey(key, newData);
    if (target) {
      // 进入编辑状态时保存原始数据
      if (!target.editable) {
        cacheOriginData[key] = {...target};
        setCacheOriginData(cacheOriginData)
      }
      target.editable = !target.editable;
      if (type === 'save'){
        saveFunction(newData)
      }else {
        setData(newData);
      }
    }
  };

  return (
    <>
      <ProTable
        toolBarRender={false}
        loading={loading}
        columns={columns}
        dataSource={data}
        search={false}
        pagination={false}
        rowClassName={(record) => (record.editable ? styles.editable : '')}
      />

    </>
  )
};

export default EditOvertimeSporadicTable;

